from typing import Optional, List, Dict, Any
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
import uuid

from models.proofmapper import ProofmapperSnapshot


async def create_snapshot(
    db: AsyncSession,
    *,
    assessment_type: str,
    name: str,
    evaluation_items: List[Dict[str, Any]],
) -> ProofmapperSnapshot:
    """创建新快照"""
    snapshot = ProofmapperSnapshot(
        id=str(uuid.uuid4()),
        assessment_type=assessment_type,
        name=name,
        evaluation_items=evaluation_items,
    )
    db.add(snapshot)
    await db.commit()
    await db.refresh(snapshot)
    return snapshot


async def get_snapshot_by_id(
    db: AsyncSession,
    snapshot_id: str,
) -> Optional[ProofmapperSnapshot]:
    """根据 ID 获取单个快照"""
    result = await db.execute(
        select(ProofmapperSnapshot).where(ProofmapperSnapshot.id == snapshot_id)
    )
    return result.scalars().first()


async def get_snapshots_by_assessment_type(
    db: AsyncSession,
    assessment_type: str,
) -> List[ProofmapperSnapshot]:
    """获取指定 assessment_type 下的所有快照（按时间倒序）"""
    result = await db.execute(
        select(ProofmapperSnapshot)
        .where(ProofmapperSnapshot.assessment_type == assessment_type)
        .order_by(ProofmapperSnapshot.saved_at.desc())
    )
    return list(result.scalars().all())


async def update_snapshot(
    db: AsyncSession,
    snapshot_id: str,
    *,
    name: Optional[str] = None,
    evaluation_items: Optional[List[Dict[str, Any]]] = None,
) -> Optional[ProofmapperSnapshot]:
    """更新快照"""
    snapshot = await get_snapshot_by_id(db, snapshot_id)
    if not snapshot:
        return None

    if name is not None:
        snapshot.name = name
    if evaluation_items is not None:
        snapshot.evaluation_items = evaluation_items

    await db.commit()
    await db.refresh(snapshot)
    return snapshot


async def delete_snapshot(
    db: AsyncSession,
    snapshot_id: str,
) -> bool:
    """删除快照"""
    snapshot = await get_snapshot_by_id(db, snapshot_id)
    if not snapshot:
        return False

    await db.delete(snapshot)
    await db.commit()
    return True
